﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Ent;

namespace Travel.MVC
{
    /// <summary>
    /// 授权筛选器基类
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
    public abstract class AuthorizeAttributeBase : FilterAttribute, IAuthorizationFilter
    {
        /// <summary>
        /// 控制器
        /// </summary>
        protected Controllers.ControllerBase Controller { get; set; }

        /// <summary>
        /// AuthorizationContext
        /// </summary>
        protected AuthorizationContext FilterContext { get; set; }

        /// <summary>
        /// 当前用户票据
        /// </summary>
        protected UserTicket CurrentUser { get; set; }

        /// <summary>
        /// 在需要授权时调用。
        /// </summary>
        /// <param name="filterContext">筛选器上下文。</param>
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            this.FilterContext = filterContext;
            this.Controller = filterContext.Controller as Controllers.ControllerBase;
            this.CurrentUser = this.Controller.CurrentUser;
            var loginUrl = string.Concat(this.Controller.Url.Action("bbb", "Default1"), "?rurl=", filterContext.HttpContext.Server.UrlEncode(filterContext.HttpContext.Request.Url.PathAndQuery));
            if (!this.IsLogined())
            {
                filterContext.Result = new RedirectResult(loginUrl);
                return;
            }
            if (!this.IsAuthorized())
            {
                this.UnAuthorizedProcess();
                return;
            }
        }

        /// <summary>
        /// 未通过权限验证的处理
        /// </summary>
        protected abstract void UnAuthorizedProcess();

        /// <summary>
        /// 判断是否通过其他验证
        /// </summary>
        /// <returns>
        ///   <c>true</c> if this instance is authorized; otherwise, <c>false</c>.
        /// </returns>
        protected abstract bool IsAuthorized();

        /// <summary>
        /// 判断是否已经登录
        /// </summary>
        /// <returns>true:已经登录 false:未登录</returns>
        private bool IsLogined()
        {
            return this.CurrentUser != null && !this.CurrentUser.IsGuest;
        }
    }
}